package service

import (
	"github.com/google/uuid"
	"golang.org/x/crypto/bcrypt"
	"guard/internal/app/admin/models"
	"guard/internal/errors"
	"guard/internal/tool"
)

func (s *adminServiceImpl) ClientPage(current, size int) (*tool.Paginator, error) {
	clientPage := s.st.SelClientPage(current, size)
	if clientPage == nil {
		return nil, errors.OtherError("分页异常")
	}

	var cdt []models.ClientDto
	client := clientPage.Data.([]models.ClientInfo)
	for _, m := range client {
		dto := models.NewClientDto(&m)
		cdt = append(cdt, *dto)
	}

	clientPage.Data = cdt

	return clientPage, nil
}

func (s *adminServiceImpl) QueryClient(condition string) (mc []models.ClientDto, err error) {
	mcs, err := s.st.SelClientQuery(condition, condition)
	if err != nil {
		return nil, errors.OtherError("查询失败")
	}
	if mcs.ClientName == "" || len(mcs.ClientName) < 0 {
		return nil, nil
	}
	var cdt []models.ClientDto
	dto := models.NewClientDto(mcs)
	cdt = append(cdt, *dto)
	return cdt, nil
}

func (s *adminServiceImpl) AddClient(info *models.ClientInfo) error {

	// 没有主键，得查询一次
	clientInfo, _ := s.st.SelClientQuery(info.ClientId, info.ClientName)

	// 创建
	if clientInfo.ClientId == "" || len(clientInfo.ClientId) <= 0 {
		info.Id = uuid.New().String()
		info.ClientId = tool.CreateClientId()

		password, err := bcrypt.GenerateFromPassword([]byte(info.ClientSecret), bcrypt.DefaultCost)
		if err != nil {
			return errors.OtherError("添加失败，密码加密失败")
		}

		info.ClientSecret = string(password)

		err = s.st.SaveClient(*info)
		if err != nil {
			return errors.OtherError("保存客户端失败")
		}
		return nil
	} else {
		// 否则，是更新
		info.ClientSecret = clientInfo.ClientSecret
		err := s.st.UpdateClient(*info)
		if err != nil {
			return errors.OtherError("更新客户端失败")
		}
		return nil
	}
}

func (s *adminServiceImpl) RemoveClient(id string) error {

	err := s.st.DelClient(id)

	if err != nil {
		return errors.OtherError("删除信息表失败")
	}

	return nil
}
